using System;
using System.Security.Cryptography;
using System.Text;

public class RSAAndAES256:IEncode,IDecode
{
    private RSAEncode m_RSAEncode;
    
    //private byte[] m_EncryAESKey;
    
    public const int EncryAESKeyLength = 128;
    
    public RSAAndAES256(RSAParameters rsaParameters)
    {
        m_RSAEncode = new RSAEncode(rsaParameters);
    }

    string NewAESKey()
    {
        string AESKey = Guid.NewGuid().ToString().Replace("-","").Substring(0,32);

        return AESKey;
    }
    
    /// <summary>
    /// 使用AES加密内容，RSA加密AES的key
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public byte[] Encrypt(byte[] data)
    {
        //每次都生成新AESKey
        string AESKey = NewAESKey();
        
        byte[] encryAESKey = m_RSAEncode.Encrypt(Encoding.UTF8.GetBytes(AESKey));
        
        //m_EncryAESKey = encryAESKey;
        //GameDebug.LogError($"AESKey:{AESKey}  encryAESKey length:{encryAESKey.Length}\n");
        
        data = AES256Encode.AESEncode(data,AESKey,Encoding.UTF8);
        
        byte[] res = new byte[encryAESKey.Length + data.Length];
        Array.Copy(encryAESKey,res,encryAESKey.Length);
        Array.Copy(data,0,res,encryAESKey.Length,data.Length);
        return res;
    }

    public byte[] Decrypt(byte[] data)
    {
        if (data.Length < EncryAESKeyLength)
        {
            GameDebug.LogError($"RSAAndAES256 decrypt error dataLength:{data.Length} < EncryAESKeyLength");
            return null;
        }
        byte[] encryAESKey = new byte[EncryAESKeyLength];
        Array.Copy(data, encryAESKey, encryAESKey.Length);
        
        byte[] content = new byte[data.Length - EncryAESKeyLength];
        Array.Copy(data,EncryAESKeyLength,content,0,content.Length);

        encryAESKey = m_RSAEncode.Decrypt(encryAESKey);
        //GameDebug.LogError($"解析出来的AESKey:{Encoding.UTF8.GetString(encryAESKey)}");
        return AES256Encode.AESDecode(content,encryAESKey);
    }
}